/**
 * 启动相关路由
 * 处理飞书登录、回调、会话管理等
 * @format
 */

const express = require("express");
const { startLoginPageUrl, getUserAccessToken, refreshUserAccessToken, getUserInfo } = require("../utils/feishu");
const { successResponse, errorResponse, unauthorizedResponse } = require("../middleware/responseHandler");
const { asyncHandler } = require("../middleware/errorHandler");
const { getUser } = require("../utils/getUser");
const logger = require("../utils/logger");

const router = express.Router();

/**
 * 设置session token信息的辅助函数
 */
const setSessionToken = (req, tokenData) => {
  const { access_token, refresh_token, expires_in } = tokenData;
  req.session.feishuAuth = {
    access_token,
    refresh_token,
    expires_in,
    loginTime: new Date().toISOString(),
  };
  const cookieMaxAge = Math.min(expires_in * 1000, 2 * 60 * 60 * 1000);
  req.session.cookie.maxAge = cookieMaxAge;
  return cookieMaxAge;
};

// 测试路由
router.get("/test", (req, res) => {
  successResponse(res, {
    timestamp: new Date().toLocaleTimeString(),
    version: "v4.0.0",
  }, "测试成功");
});

// 获取登录URL
router.get("/login", asyncHandler(async (req, res) => {
  const startUrl = startLoginPageUrl();
  successResponse(res, { startUrl }, "获取登录URL成功");
}));

// 回调处理，获取用户信息
router.post("/callback", asyncHandler(async (req, res) => {
  const { code } = req.body;
  logger.debug("收到登录回调", { code });

  if (!code) {
    return errorResponse(res, "缺少授权码", 400);
  }

  try {
    const tokenData = await getUserAccessToken(code);
    const cookieMaxAge = setSessionToken(req, tokenData);
    const { expires_in, access_token } = tokenData;

    // 获取用户信息
    const userInfo = await getUserInfo(access_token);
    req.session.userInfo = userInfo;

    // 从数据库获取用户信息
    if (userInfo.union_id) {
      const user = await getUser(userInfo.union_id);
      if (user) {
        req.session.userInfo = user;
      } else {
        logger.warn("用户信息查询失败", { union_id: userInfo.union_id });
      }
    }

    successResponse(res, {
      user: req.session.userInfo,
      sessionId: req.sessionID,
      tokenInfo: {
        expiresIn: expires_in,
        sessionMaxAge: cookieMaxAge / 1000,
      },
    }, "登录成功，token已存储到session");
  } catch (error) {
    logger.error("飞书登录回调处理失败", error);
    errorResponse(res, "飞书登录失败", 400, error.message);
  }
}));

// 获取当前session中的用户信息
router.get("/session", (req, res) => {
  if (req.session.feishuAuth?.access_token && req.session.userInfo) {
    successResponse(res, {
      user: req.session.userInfo,
    }, "用户已登录");
  } else {
    unauthorizedResponse(res, "用户未登录或session已过期");
  }
});

// 清除session（登出）
router.post("/logout", (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      logger.error("登出失败", err);
      return errorResponse(res, "登出失败", 500, err.message);
    }
    res.clearCookie("connect.sid");
    successResponse(res, null, "已成功登出");
  });
});

// 刷新token的路由
router.post("/refresh", asyncHandler(async (req, res) => {
  if (!req.session.feishuAuth?.refresh_token) {
    return unauthorizedResponse(res, "没有有效的refresh_token");
  }

  try {
    const newTokenData = await refreshUserAccessToken(req.session.feishuAuth.refresh_token);
    const cookieMaxAge = setSessionToken(req, newTokenData);
    const { expires_in } = newTokenData;

    successResponse(res, {
      sessionId: req.sessionID,
      tokenInfo: {
        expiresIn: expires_in,
        sessionMaxAge: cookieMaxAge / 1000,
      },
    }, "Token刷新成功");
  } catch (error) {
    logger.error("Token刷新失败", error);
    // 刷新失败，清除session
    req.session.destroy((err) => {
      if (err) {
        logger.error("清除session失败", err);
      }
    });
    unauthorizedResponse(res, "Token刷新失败，请重新登录");
  }
}));

module.exports = router;
